package cn.anc.aonicardv.module.ui.recorder;

import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import cn.anc.aonicardv.Constant;
import cn.anc.aonicardv.MyApplication;
import cn.anc.aonicardv.R;
import cn.anc.aonicardv.bean.AlbumBean;
import cn.anc.aonicardv.bean.PhotoBean;
import cn.anc.aonicardv.bean.VideoBean;
import cn.anc.aonicardv.event.AllSelectEvent;
import cn.anc.aonicardv.event.DeleteEvent;
import cn.anc.aonicardv.event.DownLoadEvent;
import cn.anc.aonicardv.event.MoveEvent;
import cn.anc.aonicardv.event.PlayVideoDataEvent;
import cn.anc.aonicardv.event.RecorderShareEvent;
import cn.anc.aonicardv.event.RecorderVideoDataEvent;
import cn.anc.aonicardv.event.VideoListDataEvent;
import cn.anc.aonicardv.module.adpter.listener.OnAlbumItemClickListener;
import cn.anc.aonicardv.module.adpter.listener.OnAlbumItemLongClickListener;
import cn.anc.aonicardv.module.adpter.recorder.RecorderVideoAdapter;
import cn.anc.aonicardv.module.ui.base.BaseFragment;
import cn.anc.aonicardv.util.ActivityUtils;
import cn.anc.aonicardv.util.AoniBeanDecorationUtils;
import cn.anc.aonicardv.util.DateUtils;
import cn.anc.aonicardv.util.DialogUtils;
import cn.anc.aonicardv.util.FileUtils;
import cn.anc.aonicardv.util.ListUtils;
import cn.anc.aonicardv.util.LogUtil;
import cn.anc.aonicardv.util.SpUtils;
import cn.anc.aonicardv.util.ViewUtil;
import cn.anc.aonicardv.widget.AlbumDecoration;
import cn.anc.aonicardv.widget.CommonDecoration;
import cn.anc.aonicardv.widget.RecorderAlbumDownloadDialog;
import cn.anc.httpcontrolutil.CarControl;
import cn.anc.httpcontrolutil.CarControlCommand;
import cn.anc.httpcontrolutil.cache.CacheManager;

/**
 * Created by yangdai on 2017/5/18.
 */

public class RecorderVideoFragment extends BaseFragment implements CarControl.OnCarControlCallback, View.OnClickListener, OnAlbumItemClickListener, OnAlbumItemLongClickListener {

    private static String TAG = RecorderVideoFragment.class.getSimpleName();
    private RecyclerView videoRv;
    private RecorderVideoAdapter videoAdapter = null;
    private List<VideoBean> videoBeanList = null;
    private List<AlbumBean> mAlbumList = new ArrayList<>();
    private int startIndex;
    private List<VideoBean> downloadVideoBeans = new ArrayList<>();
    public List<AlbumDecoration.DecorationBean> decorationBeanList;
    private RecorderAlbumActivity recorderAlbumActivity;
    private ProgressDialog progressDialog;
    private boolean isSharing;
    private RecorderAlbumDownloadDialog albumDownloadDialog;
    private DialogUtils dialogUtils;
    private GridLayoutManager gridLayoutManager;

    private Handler mHandler = new Handler();
    private View mLayoutNoDataView;
    private int mPage = 1;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return initView(R.layout.fragment_recorder_video);
    }

    @Override
    public void initVariable() {
        recorderAlbumActivity = (RecorderAlbumActivity) getActivity();
        dialogUtils = new DialogUtils();
        progressDialog = dialogUtils.getProgressDialog(getActivity());
        gridLayoutManager = null;
    }

    private LinearLayout mLlRootData;
    private TextView mTvUp, mTvDowm, mTvPage;

    @Override
    public void findViewById(View view) {
        mLlRootData = view.findViewById(R.id.ll_root_data);
        mTvPage = view.findViewById(R.id.tv_page);
        mTvUp = view.findViewById(R.id.tv_up);
        mTvUp.setOnClickListener(this);
        mTvDowm = view.findViewById(R.id.tv_dowm);
        mTvDowm.setOnClickListener(this);
        mLayoutNoDataView = view.findViewById(R.id.layout_no_data_view);
        videoRv = view.findViewById(R.id.rv_video);
        videoRv.setLayoutManager(new GridLayoutManager(getActivity(), mPageNum/2){
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        });
        videoRv.addItemDecoration(new CommonDecoration(getActivity()));
        videoAdapter = new RecorderVideoAdapter( this);
        videoAdapter.registerEventBusForAdapter();
        videoAdapter.setOnItemClickListener(this);
        videoAdapter.setOnItemLongClickListener(this);

        videoRv.setAdapter(videoAdapter);




    }


    @Override
    public void setListener() {


    }



    @Override
    public void initData() {
        if (!EventBus.getDefault().isRegistered(this))
            EventBus.getDefault().register(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(AllSelectEvent event) {
        if (mAlbumList == null || !getUserVisibleHint()) {
            return;
        }
        for (AlbumBean p : mAlbumList) {
            p.setCheck(event.isAllSelect);
        }

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MoveEvent event) {
        if (isReturn()) {
            return;
        }
        deletedAlbums = new ArrayList<>();
        deletedVideos = new ArrayList<>();
        deletedPaths = new ArrayList<>();
        for (AlbumBean albumBean : mAlbumList) {
            if (albumBean.isCheck()) {
                deletedAlbums.add(albumBean);
                deletedVideos.addAll(albumBean.getVideoBeanList());
            }
        }
        for (VideoBean videoBean : deletedVideos) {
            deletedPaths.add(videoBean.getPath()+"");
        }
        startIndex = 0;
        moveFileByCount(deletedPaths, startIndex);
        progressDialog.setMessage(getString(R.string.recorder_album_move_file_hint));
        progressDialog.setCancelable(false);
        progressDialog.show();


    }
    private List<AlbumBean> deletedAlbums = null;
    private List<VideoBean> deletedVideos = null;
    private List<String> deletedPaths = null;
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(DeleteEvent event) {
        if (isReturn()) {
            return;
        }
        deletedAlbums = new ArrayList<>();
        deletedVideos = new ArrayList<>();
        deletedPaths = new ArrayList<>();
        for (AlbumBean albumBean : mAlbumList) {
            if (albumBean.isCheck()) {
                deletedAlbums.add(albumBean);
                deletedVideos.addAll(albumBean.getVideoBeanList());
            }
        }
        for (VideoBean videoBean : deletedVideos) {
            deletedPaths.add(videoBean.getPath()+"");
        }
        startIndex = 0;
        deleteFileByCount(deletedPaths, startIndex);
        progressDialog.setMessage(getString(R.string.recorder_album_delete_file_hint));
        progressDialog.setCancelable(false);
        progressDialog.show();
    }
    private int delete_num = 10;
    private void moveFileByCount(List<String> temp, int startIndex) {
        if (temp.size() > 0 && temp.size() <= delete_num) {
            CarControl.doMoveFile(CarControlCommand.CarMediaType.CAR_MEDIA_TYPE_NORMAL_VIDEO, temp, this);
        } else {
            int remain = temp.size() % delete_num;
            if (temp.size() - startIndex == remain) {
                CarControl.doMoveFile(CarControlCommand.CarMediaType.CAR_MEDIA_TYPE_NORMAL_VIDEO, ListUtils.subList(temp, startIndex, temp.size() - 1), this);
            } else {
                CarControl.doMoveFile(CarControlCommand.CarMediaType.CAR_MEDIA_TYPE_NORMAL_VIDEO, ListUtils.subList(temp, startIndex, startIndex + delete_num - 1), this);
            }
        }
    }


    private void deleteFileByCount(List<String> temp, int startIndex) {
        if (temp.size() > 0 && temp.size() <= delete_num) {
            CarControl.doDeleteFile(CarControlCommand.CarMediaType.CAR_MEDIA_TYPE_EVENT_VIDEO, temp, this);
        } else {
            int remain = temp.size() % delete_num;
            if (temp.size() - startIndex == remain) {
                CarControl.doDeleteFile(CarControlCommand.CarMediaType.CAR_MEDIA_TYPE_EVENT_VIDEO, ListUtils.subList(temp, startIndex, temp.size() - 1), this);
            } else {
                CarControl.doDeleteFile(CarControlCommand.CarMediaType.CAR_MEDIA_TYPE_EVENT_VIDEO, ListUtils.subList(temp, startIndex, startIndex + delete_num - 1), this);
            }
        }
    }

    private void removeDeletedPhotos() {
        mAlbumList.removeAll(deletedAlbums);
        videoBeanList.removeAll(deletedVideos);
        resetItemPosition();
        refreshUi();
    }

    private boolean isReturn() {
        return mAlbumList == null || mAlbumList.isEmpty() || !getUserVisibleHint();
    }


    public int getVideoNum() {
        return mAlbumList == null ? 0 : mAlbumList.size();
    }

    @Override
    public void onResume() {
        super.onResume();
            refreshUi();
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onMessageEvent(RecorderVideoDataEvent event) {
        if (event.videoBeanList != null) {
            videoBeanList = event.videoBeanList;
            AlbumBean.invertOrderList(videoBeanList);
            mAlbumList.clear();
            mAlbumList.addAll(AlbumBean.getClassifyAlbumBeanByVideoBean(videoBeanList));
            for (int i = 0; i < mAlbumList.size(); i++) {
                mAlbumList.get(i).setItemPosition(i);
            }
            mPage = 1;
            setMaxPage();
            mTvPage.setText(mPage + "/" + mMaxPage);
            refreshUi();
        }

    }



    private List<AlbumBean> mCurrentList = null;
    private void refreshUi() {
        if (mAlbumList == null || mAlbumList.size()==0) {
            ViewUtil.showContentLayout(Constant.LAYOUT_EMPTY, mLayoutNoDataView, videoRv, R.mipmap.video_empty, getActivity().getResources().getString(R.string.video_empty_hint));
        } else {
            ViewUtil.showContentLayout(Constant.LAYOUT_DATA, mLayoutNoDataView, videoRv);
            mCurrentList = listSplitOfPage(mAlbumList);
            videoAdapter.refreshDataList(mCurrentList);
        }

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        LogUtil.e("llcTest0217","onActivityResult resultCode:"+resultCode);
        if (getUserVisibleHint() && resultCode == 200) {
            resetItemPosition();
            refreshUi();
        }
    }

    private void resetItemPosition() {
        for (int i = 0; i < mAlbumList.size(); i++) {
            mAlbumList.get(i).setItemPosition(i);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        if (videoAdapter != null)
            videoAdapter.unregisterEventBusForAdapter();
    }

    @Override
    public void OnCommandCallback(int code, CarControl.CommandResponseInfo info) {
        if (code != 0) {
            return;
        }
        switch (info.msg_id) {
            case CarControlCommand.CAR_CONTROL_COMMAND_ID_DELETE_FILE:
                FileUtils.deleteLocalFile(deletedPaths, startIndex, delete_num);
                startIndex += delete_num;
                if (startIndex < deletedPaths.size()){
                    deleteFileByCount(deletedPaths, startIndex);
                }
                else {
                    if (!isDetached()) {
                        progressDialog.dismiss();
                        Toast.makeText(MyApplication.getInstance(), getString(R.string.delete_success), Toast.LENGTH_SHORT).show();
                    }
                    removeDeletedPhotos();
                }
                break;
            case CarControlCommand.CAR_CONTROL_COMMAND_ID_MOVE_FILE:
                FileUtils.deleteLocalFile(deletedPaths, startIndex, delete_num);
                startIndex += delete_num;
                if (startIndex < deletedPaths.size())
                    moveFileByCount(deletedPaths, startIndex);
                else {
                    if (!isDetached()) {
                        progressDialog.dismiss();
                        Toast.makeText(MyApplication.getInstance(), getString(R.string.move_success), Toast.LENGTH_SHORT).show();
                    }
                    removeDeletedPhotos();
                }
                break;
            default:
                break;
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_up:
                if (mPage > 1 && mMaxPage > 0 && mPage <= mMaxPage) {
                    mPage--;
                    refreshUi();
                }
                break;
            case R.id.tv_dowm:
                if (mMaxPage > 0 && mPage < mMaxPage) {
                    mPage++;
                    refreshUi();
                }
                break;

        }
    }

    private int mMaxPage = 0;
    private int mPageNum = 8;
    private void setMaxPage() {
        //获取总页数
        int maxPage = mAlbumList.size() / mPageNum;
        if (maxPage * mPageNum < mAlbumList.size()) {
            maxPage++;
        }
        mMaxPage = maxPage;
    }

    private List<AlbumBean> listSplitOfPage(List<AlbumBean> mList) {
        List<AlbumBean> mBeanList = new ArrayList<>();
        if (null == mList || mList.size() == 0 || mPage < 1) {
            mPage = 1;
        } else {
            //获取总页数
            int maxPage = mList.size() / mPageNum;
            if (maxPage * mPageNum < mList.size()) {
                maxPage++;
            }
            mMaxPage = maxPage;
            if (mPage > maxPage) {
                mPage = maxPage;
            }
            mTvPage.setText(mPage + "/" + mMaxPage);
            //通过当前页码获取当前应该显示的数据list
            int index = 0;
            for (int i = 0; i < mPageNum; i++) {
                index = (mPage - 1) * mPageNum + i;
                if (index < mList.size()) {
                    mBeanList.add(mList.get(index));
                } else {
                    break;
                }
            }
        }
        return mBeanList;

    }

    @Override
    public void onItemClick(CheckBox selectCb, int position, boolean isEditMode) {
        if (!isEditMode) {
            int clickPosition = (mPage - 1) * mPageNum + position;
            LogUtil.e("llcTest0217","onItemClick clickPosition:"+clickPosition);
            ActivityUtils.jumpActivityForResult(getActivity(), RecorderVideoListActivity.class, Constant.IntentKeyParam.VIDEO_DATE, mAlbumList.get(clickPosition).getDate(),10001);
            EventBus.getDefault().postSticky(new VideoListDataEvent(mAlbumList.get(clickPosition).getVideoBeanList()));
        } else {
            selectCb.setPressed(true);
            if (selectCb.isChecked()) {
                selectCb.setChecked(false);
            } else
                selectCb.setChecked(true);
            selectCb.setPressed(false);
        }
    }

    @Override
    public void onItemLongClick(View view, int position, boolean isEditMode) {
        recorderAlbumActivity.select();
    }
}
